package com.bee.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.bee.utils.CryptographyUtil;

public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("login doGet");
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("login doPost");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		password = CryptographyUtil.md5(userName + "$" + password, "bee");

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		try {
			// 启用Shiro的Remenber Me支持（记录于Cookie中）
			if (subject.isRemembered()) {
				System.out.println("已经isRememberMe");
			} else {
				token.setRememberMe(true); // 这个功能可以自己封装
			}

			// 调用login()之后会跑到自定义realm（MyRealm）的doGetAuthenticationInfo()。
			subject.login(token);

			// 使用Shiro实现的session
			Session session = subject.getSession();
			System.out.println("Shiro.session id：" + session.getId());
			System.out.println("Shiro.session host：" + session.getHost());
			System.out.println("Shiro.session timeout：" + session.getTimeout()); // 默认30分钟
			session.setAttribute("info", "Shiro session里边也可以放数据，和HttpServlet.session一样。");

			response.sendRedirect("success.jsp"); // 登陆成功Shiro会在底层记录会话session
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorInfo", "用户名或者密码错误");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}